import Taro from '@tarojs/taro'
import host from '../config/host'
import {IApi} from '../intfaces'

export default async function(api: IApi, params: any = null, headers:any = {}): Promise<any> {
  const method = api.method.toUpperCase()
  const url = host + api.url
  headers['timestamp'] = parseInt(`${(new Date().getTime())/1000}`)
  if (method === 'POST') {
    headers['Content-Type'] = 'application/json'
  }else if (method === 'GET') {
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }
  headers['token'] = await Taro.getStorageSync('token') || ''
  let opts:any = {
    isShowLoading: true,
    loadingText: '正在加载',
    url: url,
    method: method
  }
  if (params) opts.data = params
  const resp = await Taro.request({
    ...opts,
    headers: headers
  })
  let data: any
  if (resp.statusCode === 200 && resp.data.code === 200) {
    if (resp.data.data.Token) {
      Taro.setStorageSync('token', resp.data.data.Token)
      delete resp.data.data.Token
    }
    data = resp.data.data
  } else {
    await Taro.showToast({
      title: resp.data.tip || '未知错误',
      duration: 2000,
      mask: false,
      icon: 'none'
    })
  }
  return data
}
